package yicr;



import javax.swing.*;
import javax.swing.border.Border;
import javax.swing.filechooser.FileFilter;
import javax.swing.filechooser.FileNameExtensionFilter;
import java.awt.*;
import java.io.File;
import java.io.UnsupportedEncodingException;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.List;

/**
 * <h3>Title:</h3>
 * <p>
 *
 * <h3>Description</h3>
 * <p>
 *
 * <h3>Author</h3>
 * <p>
 * Lin Shao
 * <h3>Update Time</h3>
 * <p>2021-10-23 20:59
 *
 * @author Lin Shao
 * @version 1.0
 */
public class CalFrame extends JFrame {
    private Form form=null;
    private int geohashColumnIndex;

    private static final int DEFAULT_WIDTH=740;
    private static final int DEFAULT_HEIGHT=340;

    private JTextField cityMaxDistance=null;
    private JTextField suburbMaxDistance=null;
    private JTextField ruralMaxDistance=null;
    private JTextField recordState=null;

    private int defaultCityMaxDistance=20;
    private String defaultSuburbMaxDistance="longitude";
    private String defualtRuralMaxDistance="latitude";

    private JButton importDataButton=null;
    private JButton calDataButton=null;

    private JFileChooser fileChooser=null;
    private String importFileAbsPath;

    private List<String> lineList =null;


    public CalFrame () throws URISyntaxException {
        initFont();



        //lineList=new ArrayList<>();
        lineList =new ArrayList<>();

        setSize(new Dimension(DEFAULT_WIDTH,DEFAULT_HEIGHT));
        setResizable(false);

        fileChooser=new JFileChooser();

        FileFilter filter = new FileNameExtensionFilter(
                "Csv files", "csv");
        fileChooser.setFileFilter(filter);


        System.setProperty("exe.path","Z:\\GS_Dir_Zdisk\\GS#i3#Work\\2021SJY\\软课题\\AD\\v4");
        String basePath=System.getProperty("exe.path");




        JLabel suburbLabel= null;
        JLabel cityLabel=null;
        JLabel ruralLabel=null;
        JLabel exeStateLabel=null;


       // System.out.println(new File("").getAbsolutePath());

        String exePath=new File("").getAbsolutePath()+"\\";

        setIconImage(new ImageIcon(exePath+"res\\xml_1.jpg").getImage());

        try {
            cityLabel=new JLabel(new String(basePath.getBytes(),"GB2312"));
            cityLabel=new JLabel("Geohash  Bit设置:");

            //new String(value.getBytes("ISO8859-1"), encoding)
            suburbLabel=new JLabel(" 经度对应列名称: ");
            //suburbLabel = new JLabel(new String(basePath.getBytes("ISO8859-1"),"GBK"));

            ruralLabel=new JLabel(" 纬度对应列名称: ");
            //ruralLabel=new JLabel(new String(new File("").getAbsolutePath()));
            exeStateLabel=new JLabel("Ott数据导入状态:");

            //exeStateLabel=new JLabel(new String(new File("/").getAbsolutePath()));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        cityMaxDistance=new JTextField();
        suburbMaxDistance=new JTextField();
        ruralMaxDistance=new JTextField();
        recordState=new JTextField();

        int textColumn=15;

        cityMaxDistance.setColumns(textColumn);
        suburbMaxDistance.setColumns(textColumn);
        ruralMaxDistance.setColumns(textColumn);
        recordState.setColumns(textColumn);



        importDataButton=new JButton("导入原始数据");
        calDataButton=new JButton("Geohash汇聚导出");



        JLabel meterLabel1=new JLabel("位");
        JLabel meterLabel2=new JLabel(" ");
        JLabel meterLabel3=new JLabel(" ");
        JLabel recordUnitLabel=new JLabel("条");

        cityMaxDistance.setHorizontalAlignment(JTextField.CENTER);
        suburbMaxDistance.setHorizontalAlignment(JTextField.CENTER);
        ruralMaxDistance.setHorizontalAlignment(JTextField.CENTER);
        recordState.setHorizontalAlignment(JTextField.CENTER);

        cityMaxDistance.setText(defaultCityMaxDistance+"");
        suburbMaxDistance.setText(defaultSuburbMaxDistance+"");
        ruralMaxDistance.setText(defualtRuralMaxDistance+"");
        recordState.setText("未导入数据");
        //recordState.setText("已导入10000");

        recordState.setEditable(false);
        recordState.setForeground(Color.RED);

        //String imageAbsPath= getClass().getClassLoader().getResource(".").toURI().getPath()+ "/yicr/antenna_1.png";
        String imageAbsPath="d:/antenna_1.png";
        //imageAbsPath=exePath+"res\\antenna_1.png";
        System.out.println(Thread.currentThread().getContextClassLoader().getResource(""));
        //imageAbsPath=Thread.currentThread().getContextClassLoader().getResource("")+"\\antenna_1.png";
        //imageAbsPath=Thread.currentThread().getContextClassLoader().getResource("")+"\\antenna_1.png";
        imageAbsPath=Thread.currentThread().getContextClassLoader().getResource("")+"\\geohash_2_f.png";
        //imageAbsPath=Thread.currentThread().getContextClassLoader().getResource("")+"\\antenna_1.png";
        imageAbsPath=imageAbsPath.replace("file:","");

        //System.out.println(new File(imageAbsPath).getAbsolutePath());
        JLabel imageLabel=new JLabel(new ImageIcon(imageAbsPath));
        Border etched = BorderFactory.createEtchedBorder();
        imageLabel.setBorder(etched);

        JPanel parameterPanel=new JPanel();

        GridBagLayout gridBagLayoutOfParameterPanel=new GridBagLayout();

        parameterPanel.setLayout(gridBagLayoutOfParameterPanel);

        int top=20;
        int bottom=20;

        parameterPanel.add(cityLabel,new GBC(0,0,1,1).setAnchor(GridBagConstraints.EAST).setInsets(top,30,15,20));
        parameterPanel.add(suburbLabel,new GBC(0,1,1,1).setAnchor(GridBagConstraints.EAST).setInsets(15,30,15,20));
        parameterPanel.add(ruralLabel,new GBC(0,2,1,1).setAnchor(GridBagConstraints.EAST).setInsets(15,30,15,20));
        parameterPanel.add(exeStateLabel,new GBC(0,3,1,1).setAnchor(GridBagConstraints.EAST).setInsets(15,30,bottom,20));

        parameterPanel.add(cityMaxDistance,new GBC(1,0,1,1).setAnchor(GridBagConstraints.EAST).setInsets(top,0,15,0));
        parameterPanel.add(suburbMaxDistance,new GBC(1,1,1,1).setAnchor(GridBagConstraints.EAST).setInsets(15,0,15,0));
        parameterPanel.add(ruralMaxDistance,new GBC(1,2,1,1).setAnchor(GridBagConstraints.EAST).setInsets(15,0,15,0));
        parameterPanel.add(recordState,new GBC(1,3,1,1).setAnchor(GridBagConstraints.EAST).setInsets(15,0,bottom,0));

        parameterPanel.add(meterLabel1,new GBC(2,0,1,1).setAnchor(GridBagConstraints.WEST).setInsets(top,5,15,10));
        parameterPanel.add(meterLabel2,new GBC(2,1,1,1).setAnchor(GridBagConstraints.WEST).setInsets(15,5,15,10));
        parameterPanel.add(meterLabel3,new GBC(2,2,1,1).setAnchor(GridBagConstraints.WEST).setInsets(15,5,15,10));
        parameterPanel.add(recordUnitLabel,new GBC(2,3,1,1).setAnchor(GridBagConstraints.WEST).setInsets(15,5,bottom,10));

        //Border etched = BorderFactory.createEtchedBorder();
        Border titled = BorderFactory.createTitledBorder(etched, "参数设置");

        parameterPanel.setBorder(titled);


        GridBagLayout mainGridBagLayout=new GridBagLayout();

        setLayout(mainGridBagLayout);

        add(parameterPanel,new GBC(0,0,2,1));
        add(importDataButton,new GBC(0,1,1,1).setInsets(15));
        add(calDataButton,new GBC(1,1,1,1).setInsets(15));



        add(imageLabel,new GBC(2,0,1,2).setInsets(5));


        setScreenCenter();
        //pack();

        addEvents();
    }

    private void addEvents() {

        importDataButton.addActionListener(e -> {
            fileChooser.setCurrentDirectory(new File("."));
            // show file chooser dialog
            int result = fileChooser.showOpenDialog(CalFrame.this);

            // if image file accepted, set it as icon of the label
            if (result == JFileChooser.APPROVE_OPTION)
            {

                form=new Form();
                //System.out.println(cityMaxDistance.getText());
                try {
                /*form.setCityCoverRange(Double.parseDouble(cityMaxDistance.getText()));
                form.setSuburbCoverRange(Double.parseDouble(suburbMaxDistance.getText()));
                form.setRuralCoverRange(Double.parseDouble(ruralMaxDistance.getText()));*/

                    form.setGeohashBit(Integer.parseInt(cityMaxDistance.getText()));
                    form.setLongitudeColumnName(suburbMaxDistance.getText());
                    form.setLatitudeColumnName(ruralMaxDistance.getText());


                }catch (NumberFormatException exception){
                    JOptionPane.showMessageDialog(CalFrame.this, "输入GeoHash位数错误。", "错误", JOptionPane.ERROR_MESSAGE);
                    return;
                }

                String name = fileChooser.getSelectedFile().getPath();
                //label.setIcon(new ImageIcon(name));
                //pack();
                System.out.println(name);
                importFileAbsPath=name;



                importDataButton.setEnabled(false);
                calDataButton.setEnabled(false);
                recordState.setText("正在导入数据");


               /* try {
                    Thread.sleep(5*1000);
                } catch (InterruptedException e1) {
                    e1.printStackTrace();
                }*/
                lineList =Calculation.importCellData(importFileAbsPath,form);

                recordState.setText("共导入数据"+ (lineList.size()-1));
                importDataButton.setEnabled(true);
                calDataButton.setEnabled(true);
                System.out.println(lineList.size());
            }
        });




        calDataButton.addActionListener(e->{

            new Thread(new Runnable() {
                @Override
                public void run() {
                    recordState.setText("正在计算Geohash");
                    //repaint();
                    //pack();
                }
            }).start();

            try {
                Thread.sleep(100);
            } catch (InterruptedException e1) {
                e1.printStackTrace();
            }


            int returnVal = fileChooser.showSaveDialog(CalFrame.this);

            if(returnVal == JFileChooser.APPROVE_OPTION){

                String outputFilePath = fileChooser.getSelectedFile().getPath();

                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        recordState.setText("正在计算Geohash");
                        repaint();
                        //pack();
                    }
                }).start();

                importDataButton.setEnabled(false);
                calDataButton.setEnabled(false);

                lineList=Calculation.calGeoHash(lineList,form);
                //String outputFilePath="Z:\\GS_Dir_Zdisk\\GS#i3#Work\\2021SJY\\软课题\\AD\\output_3.csv";
                //Calculation.exportCsv(csvList,lineList, outputFilePath);

                try {
                    Calculation.exportCsv2(lineList,outputFilePath);
                } catch (Exception ex) {
                    ex.printStackTrace();
                }


                importDataButton.setEnabled(true);
                calDataButton.setEnabled(true);

                recordState.setText("已计算数据"+ lineList.size());
            }

        });

    }


    private void initFont(){
        Font f = new Font("宋体", Font.PLAIN,12);

        String names[]={ "Label", "CheckBox", "PopupMenu","MenuItem", "CheckBoxMenuItem",
                "JRadioButtonMenuItem","ComboBox", "Button", "Tree", "ScrollPane",
                "TabbedPane", "EditorPane", "TitledBorder", "Menu", "TextArea",
                "OptionPane", "MenuBar", "ToolBar", "ToggleButton", "ToolTip",
                "ProgressBar", "TableHeader", "Panel", "List", "ColorChooser",
                "PasswordField","TextField", "Table", "Label", "Viewport",
                "RadioButtonMenuItem","RadioButton", "DesktopPane", "InternalFrame"
        };
        for (String item : names) {
            UIManager.put(item+ ".font",f);
        }
    }

    private void setScreenCenter(){

        int windowWidth = getWidth(); // 获得窗口宽
        int windowHeight = getHeight(); // 获得窗口高
        Toolkit kit = Toolkit.getDefaultToolkit(); // 定义工具包
        Dimension screenSize = kit.getScreenSize(); // 获取屏幕的尺寸
        int screenWidth = screenSize.width; // 获取屏幕的宽
        int screenHeight = screenSize.height; // 获取屏幕的高
        setLocation(screenWidth / 2 - windowWidth / 2, screenHeight / 2 - windowHeight / 2);// 设置窗口居中显示

    }


    public static void main(String[] args) {
        EventQueue.invokeLater(()->{
            CalFrame calFrame= null;
            try {
                calFrame = new CalFrame();
            } catch (URISyntaxException e) {
                e.printStackTrace();
            }
            calFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            calFrame.setVisible(true);
            calFrame.setTitle("OTT Geohash汇聚工具");
        });
    }
}
